﻿using MediatR;
using Newtonsoft.Json;
using PublicClass;
using PublicClass.HttpClient;
using S.Produce.Domains;
using S.Produce.Domains.DTO;
using S.Produce.Infrastructure;
using S.Produce.Read.Api.Application.Commands.BreedingCommands;

namespace S.Produce.Read.Api.Application.CommandHandlers.BreedingCommandHandlers
{
    public class BreedingSelectCommandHandler : IRequestHandler<BreedingSelectCommand, PageInfo<Breeding>>
    {
        private readonly IRepository<Breeding> _repository;
        private readonly ServiceHttpClient _httpClient;

        public BreedingSelectCommandHandler(IRepository<Breeding> repository, ServiceHttpClient httpClient)
        {
            _repository = repository;
            _httpClient = httpClient;
        }

        public async Task<PageInfo<Breeding>> Handle(BreedingSelectCommand request, CancellationToken cancellationToken)
        {
            var info = await _repository.GetAllAsync();
            var res = info.AsQueryable().Where(x => x.IsDel == false);
            if (!string.IsNullOrEmpty(request.BreedingDate))
            {
                var sdate = request.BreedingDate.Split(",")[0];
                var edate = request.BreedingDate.Split(",")[1];
                res = res.Where(x => x.BreedingDate >= DateTime.Parse(sdate) && x.BreedingDate <= DateTime.Parse(edate));
            }
            if (!string.IsNullOrEmpty(request.Earbugles))
            {
                res = res.Where(x => x.Earbugles.Equals(request.Earbugles));
            }
            if (!string.IsNullOrEmpty(request.Head))
            {
                res = res.Where(x => x.Head.Equals(request.Head));
            }
            int totalCount = res.Count();
            int pageCount = (int)Math.Ceiling(totalCount * 1.0 / request.pageSize);
            res = res.OrderByDescending(x => x.CreateDate).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize);
            foreach (var item in res)
            {
                //种母品种
                var zm = await _httpClient.Get("http://10.31.56.15:8090/api/SheepFile/SheepFileConditionbreed?EarNumber=" + item.Earbugles);
                item.BreedinghenType = JsonConvert.DeserializeObject<SheepTypeDto>(zm).breed; 

                //种公品种
                var zg = await _httpClient.Get("http://10.31.56.15:8090/api/SheepFile/SheepFileConditionbreed?EarNumber=" + item.ServiceRam);
                item.SeedmaleType = JsonConvert.DeserializeObject<SheepTypeDto>(zg).breed;

                //上一次配种日期
                item.LastDate = _repository.SelAllAsync(x => x.Earbugles == item.Earbugles).Result.Where(x => x.BreedingDate < item.BreedingDate).Select(x => x.BreedingDate).Max();
            }
            var result = new PageInfo<Breeding>()
            {
                datas = res.ToList(),
                pageCount = pageCount,
                totalCount = totalCount
            };
            return result;
        }
    }
}
